package com.qf.shiro2302.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.qf.shiro2302.entity.User;
import com.qf.shiro2302.service.UserService;
import com.qf.shiro2302.utils.Constants;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@RequestMapping("/login")
public class LoginController {

    @Autowired
    private UserService userService;

    @PostMapping("/do")
    public String dolog(String username,String password) throws Exception {

        // 使用shiro进行登录处理
        Subject subject = SecurityUtils.getSubject();  // 获取shiro核心对象

        // 为了调用shiro的登录方法，需要准备一个 Token对象
        UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(username,password);

        subject.login(usernamePasswordToken);  // 使用shiro的登录流程

        // 查询一下当前用户的角色和权限信息，放入 principale中
        User user = (User) subject.getPrincipal();
//        List<String> roles = userService.getRolesFromDB(user);
        List<String> roles = userService.getRolesFromDBbyMp(user);
//        List<String> permissions = userService.getPermissionsFromDB(user);
        List<String> permissions = userService.getPermissionsFromDBbyMp(user);
        user.setRoles(roles);
        user.setPers(permissions);

        return "login ok";

    }


    /**
     * 简单密码匹配器解决 md5密码的方案 （由学委提供）
     * @param username
     * @param password
     * @return
     * @throws Exception
     */
    @PostMapping("/dologin")
    public String dologin(String username,String password) throws Exception {

        // 使用shiro进行登录处理
        Subject subject = SecurityUtils.getSubject();  // 获取shiro核心对象

        User dbuser = userService.getOne(new QueryWrapper<User>().eq("username", username));
        if (dbuser==null){
            throw new Exception("用户名错了");
        }

        // 把密码转换为md5的密码
        String md5password = new Md5Hash(password, dbuser.getSalt(), Constants.HASH_TIMES).toHex();

        // 为了调用shiro的登录方法，需要准备一个 Token对象
        UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(username,md5password);

        subject.login(usernamePasswordToken);  // 使用shiro的登录流程

        return "login ok";

    }

}
